var joinroom = {}; //\n加入的房间
var user_type = "";
$('.list-group').on('click', '.list-group-item', function() {
	$('div[roomid="' + $(this).children().children('.text2').attr("rooname") + '"]').css('display', 'block');
	$('div[roomid="' + $(this).children().children('.text2').attr("rooname") + '"]').siblings().css('display', 'none');
	$(this).css("color", "#1abb9c").siblings().css("color", "");
	$(this).css("background", "#EBEBEC").siblings().css("background", "");
	$(this).children(".rights").children(".layui-bg-green").css("display", "none");
	var text1 = $(this).css("color", "#1abb9c").children(".center").children(".text1").attr("socket_name");
	var text2 = $(this).css("color", "#1abb9c").children(".center").children(".text2").attr("rooname");
	$(".username").html($(this).css("color", "#1abb9c").children(".center").children(".text1").text());
	$(".username").attr("data-id", text2);
	user_type = $(this).attr("data-type"); //记录用户类型
	let roomid = $(".username").attr("data-id");
	$('div[roomid="' + roomid + '"] input[type=date]').attr("max", moment().format('YYYY-MM-DD')); //限制时间为后来日期
	let msg = window.sessionStorage['user_msg'];
	msg = JSON.parse(msg);
	if(!joinroom[text2]) {
		//加入房间
		socket.emit("joinroom", {
			roomID: text2,
			username: $("#name").attr("data-name"),
			sex: 1,
			userrole: msg.userrole,
			token: msg.token
		});
		joinroom[text2] = text2;
	};
	//加入新的房间 退出以前房间
	//	var arrs = [...new Set(roominfos)];
	//	for(let a = 0; a < arrs.length; a++) {
	//		if(arrs[a].rooname != text2) {
	//			socket.emit("leave", {
	//				roomID: arrs[a].rooname,
	//				username: $("#name").attr("data-name"),
	//			});
	//		}
	//	};
	$(".closes").attr("data-id", text2);
	$(".closes").attr("socket_id", $(this).attr("socket_id"));
	$(".closes").attr("userphone", $(this).attr("userphone"));
	$(".chat-thread").children("li").remove();
	//判断接待列表是否为空
	dont_online();
	//判断该房间是否指派过医生
	if(assigned_doctor.includes(roomid)) {
		$(".Assigned_tothe_doctor").text("待处理");
		//$(".Assigned_tothe_doctor").attr("disabled", "disabled");
		//$(".Assigned_tothe_doctor").css("color", "#333333");
		//$(".Assigned_tothe_doctor").css("border", "1px solid #333333");
		$("div[roomid='" + roomid + "'] .modification").css("display", "block");
	} else {
		$(".Assigned_tothe_doctor").text("指派医生");
		//$(".Assigned_tothe_doctor").removeAttr("disabled", "disabled");
		$(".Assigned_tothe_doctor").css("color", "#1abb9c");
		$(".Assigned_tothe_doctor").css("border", "1px solid #1abb9c");
		$("div[roomid='" + roomid + "'] .modification").css("display", "none");
	};
	//聊天记录
	findchat({
		roomID: $(".username").attr("data-id"),
		username: $("#name").attr("data-username"),
		page: 1,
		limit: 20
	});
	//审核状态
	gettemporary(roomid);
	//layer.open({
	//		type: 1,
	//		title: ['新消息'],
	//		area: ['280px', '180px'],
	//		shade: 0,
	//		offset: 'rb',
	//		anim: 2,
	//		closeBtn: false,
	//		content: "<div  style='word-wrap: break-word;margin: 0 auto;width: 200px;text-align: center;margin-top:10px;color: black;' roomID=" + 1 + ">" + 1 + '是否立即查看！' + "</div>",
	//		btn: ['立即查看', '关闭'],
	//		btn1: function(index) {
	//			//基本信息
	//			layer.close(index);
	//			layer.open({
	//			  type: 2,
	//			  title: '电子问诊单详情',
	//			  shadeClose: true,
	//			  shade: 0.8,
	//			  area: ['90%', '90%'],
	//			  content: `../postpaper/postpaper.html?id=5a6595f69405da151725fa6d&&name=3` //iframe的url
	//			});
	//		},
	//		btn2: function(index) {
	//			layer.close(index);
	//		},
	//		zIndex: layer.zIndex,
	//		success: function(layero) {
	//			layer.setTop(layero); //重点2\
	//			layero.find(".layui-layer-title").before("<span></span>");
	//			layero.find(".layui-layer-title").css({
	//				"font-weight": "500",
	//				"width": "100%"
	//			});
	//			layero.find(".layui-layer-title").addClass("glyphicon glyphicon-cog");
	//			layero.find(".layui-layer-title").css({
	//				"font-weight": "500"
	//			});
	//			layero.find(".layui-layer-btn").css({
	//				"border-top": "1px solid rgb(240,240,240)",
	//				"text-align": "center"
	//			});
	//			layero.find(".layui-layer-btn0").css({
	//				"width": "100px",
	//				"border-color": "white",
	//				"background-color": "white",
	//				"color": "#1abb9c",
	//				"border-right": "1px solid rgb(240,240,240)"
	//			});
	//			layero.find(".layui-layer-btn1").css({
	//				"width": "100px",
	//				"border-color": "white",
	//				"background-color": "white",
	//				"color": "rgb(145, 141, 141)"
	//			})
	//		}
	//	});
});

//更新待接待人数
socket.on("newrooname", (data) => {
	console.log(data);
	$(".jiedai").text(data.length)
})
//申请接待用户
$(function() {
	$(".jierupic").on("click", function() {
		let msg = window.sessionStorage['user_msg'];
		msg = JSON.parse(msg);
		$.ajax({
			url: "http://114.55.38.80:8000/service/rooname",
			type: "post",
			dataType: "json",
			data: {
				userid: $("#name").attr("data-name")
			},
			headers: {
				'Authorization': 'Bearer ' + msg.token
			},
			success: function(res) {
				console.log(res)
				let type = "";
				let htmls = "";
				if(res.body) {
					let htmltext = $('.htmlappend').html();
					$('.rightlist').append('<div style="background: white; height: 803px; margin-top: 20px; overflow: auto;display: none" class="apendhtml"  roomid="' +
						res.body.rooname + '">' + htmltext + '</div>');
					if(res.body.marking == 1) {
						type = "pc1";
						username = res.body.socket_name
					}
					if(res.body.marking == 2) {
						type = "wx1";
						username = res.body.nickname
					}
					if(res.body.marking == 3) {
						type = "app1"
						username = res.body.socket_name
					}
					htmls +=
						`
						   <li class="list-group-item"      userphone="${res.body.userPhone}"   data-type = "${type}" rooname="${res.body.rooname}" socket_id="${res.body.socket_id}">
						   <div class="flex-item" socket_id="${res.body.socket_id}">
						   <img src="img/${type}.png" class="img"/>
						   </div>
						   <div class="flex-item center">
						   <span class="text1" socket_name="${username}">${res.body.userPhone}</span><br/>
						   <span class="text2" rooname="${res.body.rooname}"></span>
						   </div>
						   <div class="flex-item rights">
						   <span>${res.body.data}</span>
						   <span class="layui-badge-dot layui-bg-green" style="margin-left: 27px;margin-top: 10px;display: none;"></span>
						   </div>
						   </li>
						   `
				};
				$(".list-group").append(htmls);
				$(".jiedai").text(res.rooms);
				$('.list-group').children("img").remove();
				//createonclick(); //创建点击事件
				//判断接待列表是否为空
				dont_online();
			},
			error: function(err) {
				console.log(err)
			}
		})
	});
	//刷新页面请求更新列表
	$.ajax({
		url: "http://114.55.38.80:8000/service/refreshroom",
		type: "post",
		dataType: "json",
		data: {
			userid: $("#name").attr("data-name")
		},
		success: function(res) {
			console.log(res);
			var arr_all = [];
			var username = "";
			$(".list-group").children("li").remove();
			var html = "";
			var arr_s_ = [];
			var arr_new = [];
			var type = "";

			for(let a in res.body) {
				if(res.body[a]) {
					arr_s_.push(res.body[a]);
				}
			}

			for(var i = 0; i < arr_s_.length; i++) {
				let htmltext = $('.htmlappend').html();
				$('.rightlist').append('<div style="background: white; height: 803px; margin-top: 20px; overflow: auto;display: none" class="apendhtml"  roomid="' +
					arr_s_[i].rooname + '">' + htmltext + '</div>')

				//如果当前数组的第i已经保存进了临时数组，那么跳过， 
				//否则把当前项push到临时数组里面 
				if(arr_new.indexOf(arr_s_[i]) == -1) arr_new.push(arr_s_[i]);
			}
			//createonclick(); //创建点击事件
			for(let i = 0; i < arr_new.length; i++) {
				if(arr_new[i].marking == 1) {
					type = "pc1";
					username = arr_new[i].socket_name
				}
				if(arr_new[i].marking == 2) {
					type = "wx1";
					username = arr_new[i].nickname
				}
				if(arr_new[i].marking == 3) {
					type = "app1"
					username = arr_new[i].socket_name
				}
				html +=
					`
						   <li class="list-group-item"    userphone="${arr_new[i].userPhone}"      data-type = "${type}" rooname="${arr_new[i].rooname}" socket_id="${arr_new[i].socket_id}"">
						   <div class="flex-item">
						   <img src="img/${type}.png" class="img"/>
				  		   </div>
						   <div class="flex-item center">
						   <span class="text1" socket_name="${username}">${arr_new[i].userPhone}</span><br/>
						   <span class="text2" rooname="${arr_new[i].rooname}"></span>
						   </div>
						   <div class="flex-item rights">
						   <span>${arr_new[i].data}</span>
						     <span class="layui-badge-dot layui-bg-green" style="margin-left: 27px;margin-top: 10px;display: none;"></span>
						   </div>
						   </li>
						   `
			};
			$(".list-group").html(html);
			$(".jiedai").text(res.rooms);
			//判断接待列表是否为空
			dont_online();
		},
		error: function(err) {
			console.log(err)
		}
	});
	//服务器断开之后回到登陆界面
	socket.on("disconnect", function() {
		layer.open({
			title: '系统提示',
			content: '正在重连服务器',
			success: function(layero) {
				 layero.find(".layui-layer-btn0").css({
				 	"border-color":"#1abb9c",
				 	"background-color":"#1abb9c"
				 })	
			}
		});
	});
	//重新连接服务器
	socket.on("reconnect", function() {
		$.ajax({
			url: "http://114.55.38.80:8000/service/refreshroom",
			type: "post",
			dataType: "json",
			data: {
				userid: $("#name").attr("data-name")
			},
			success: function(res) {
				console.log(res);
				var arr_all = [];
				var username = "";
				$(".list-group").children("li").remove();
				var html = "";
				var arr_s_ = [];
				var arr_new = [];
				var type = "";

				for(let a in res.body) {
					if(res.body[a]) {
						arr_s_.push(res.body[a]);
					}
				}

				for(var i = 0; i < arr_s_.length; i++) {
					let htmltext = $('.htmlappend').html();
					$('.rightlist').append('<div style="background: white; height: 803px; margin-top: 20px; overflow: auto;display: none" class="apendhtml"  roomid="' +
						arr_s_[i].rooname + '">' + htmltext + '</div>')

					//如果当前数组的第i已经保存进了临时数组，那么跳过， 
					//否则把当前项push到临时数组里面 
					if(arr_new.indexOf(arr_s_[i]) == -1) arr_new.push(arr_s_[i]);
				}
				//createonclick(); //创建点击事件
				for(let i = 0; i < arr_new.length; i++) {
					if(arr_new[i].marking == 1) {
						type = "pc1";
						username = arr_new[i].rooname
					}
					if(arr_new[i].marking == 2) {
						type = "wx1";
						username = arr_new[i].nickname
					}
					if(arr_new[i].marking == 3) {
						type = "app1"
						username = arr_new[i].rooname
					}
					html +=
						`
						   <li class="list-group-item"          data-type = "${type}" rooname="${arr_new[i].rooname}" socket_id="${arr_new[i].socket_id}"">
						   <div class="flex-item">
						   <img src="img/${type}.png" class="img"/>
				  		   </div>
						   <div class="flex-item center">
						   <span class="text1">${username}</span><br/>
						   <span class="text2">${arr_new[i].rooname}</span>
						   </div>
						   <div class="flex-item rights">
						     <span>${arr_new[i].data}</span>
						     <span class="layui-badge-dot layui-bg-green" style="margin-left: 27px;margin-top: 10px;display: none;"></span>
						   </div>
						   </li>
						   `
				};
				$(".list-group").html(html);
				$(".jiedai").text(res.rooms);
				//判断接待列表是否为空
				dont_online();
			},
			error: function(err) {
				console.log(err)
			}
		});
	})
});

//关闭房间 删除接待房间信息
$('.closes').on('click', (event) => {
	event.preventDefault();
	let roomID = $(".closes").attr("data-id");

	if(!roomID) {
		layer.open({
			title: '系统提示',
			content: '请选择需要结束服务的房间',
			yes: function(index, layero){
			    //按钮【按钮一】的回调
			    layer.close(index);
			},
			success: function(layero) {
				 layero.find(".layui-layer-btn0").css({
				 	"border-color":"#1abb9c",
				 	"background-color":"#1abb9c"
				 })	
			}
		});
		return;
	}
	layer.confirm('您确定要结束服务吗？', {
		title: "系统提示",
		btn: ['确定', '取消'], //按钮
		success: function(layero) {
				 layero.find(".layui-layer-btn0").css({
				 	"border-color":"#1abb9c",
				 	"background-color":"#1abb9c"
				 })	
		}
	}, function(index) {
		layer.msg('已结束当前服务', {
			icon: 1
		});
		$(".username").html("");
		$(".chat-thread").html("");
		$.ajax({
			url: "http://114.55.38.80:8000/service/endroom",
			type: "post",
			dataType: "json",
			data: {
				roomID: roomID,
				username: $("#name").attr("data-name")
			},
			success: function(res) {
				console.log(res);
				if(res.code == 200) {
					//结束服务删除房间用户信息
					del_temporary(roomID);
					//退出房间
					socket.emit("leave", {
						roomID: roomID,
						username: $("#name").attr("data-name"),
						events: "out"
					});
					$('li[rooname="' + roomID + '"]').remove(); //移除信息展示区
					$('div[roomid="' + roomID + '"]').remove(); //移除信息展示区
					$(".username").attr("data-id", ""); //清空id
					delete joinroom[roomID]; //移除加入房间信息
					dont_online(); //判断接待列表是否为空
				}
			},
			error: function(err) {
				console.log(err)
			}
		});
	}, function() {
		layer.open({
			title: '系统提示',
			content: '您已取消结束服务',
			success: function(layero) {
				 layero.find(".layui-layer-btn0").css({
				 	"border-color":"#1abb9c",
				 	"background-color":"#1abb9c"
				 })	
			}
		});
	});
})

//$('.upload_picture')
$('.expression_upload').on('click', '.uploadImg', () => {
	var uploading = $('.uploadImg');
	$(uploading[uploading.length - 1]).on('change', function() {
		var file = this.files[0];
		console.log(file.size / 1000);
		if(file.size / 1000 >= 1024 * 5) {
			layer.open({
				title: '系统提示',
				content: '上传的图片不能大于5m,请重新选择图片!',
			});
			return
		};
		$.ajax({
			url: "https://xcx.juseyx.cn/service/uploadimg",
			type: "post",
			cache: false,
			data: new FormData($("#uploadImg")[0]),
			processData: false,
			contentType: false,
			success: function(res) {
				$('#uploadImg').html('');
				$('#uploadImg').append('<input type="file" name="files" class="uploadImg">')
				console.log(res);
				let html = `<li class="layim-chat-mine">
					<div class="layim-chat-user">
						<img src="https://xcximg.juseyun.com/Images/servers.png">
							<cite><i>${$("#name").attr("data-username")}</i>${moment().format('hh:mm:ss')}</cite>
							</div>
						<div class="layim-chat-text" style="color:white;background-color:#1abb9c;" >
						   <img class="chatimg" src="${res.data}">
						</div>
				   </li>`
				$('.chat-thread').append(html);
				let pars = {
					roomID: $(".username").attr("data-id"),
					username: $("#name").attr("data-username"),
					userRole:$("#name").attr("userrole"),
					type: "msg",
					msg: "",
					b: 1,
					anonymityImg: "https://xcximg.juseyun.com/Images/servers.png",
					color: false,
					imggs: res.data,
					id: 0,
					is: $("#name").attr("data-username"),
				};
				socket.emit("message", pars);
				//聊天记录
				//chatrecord(pars);
			},
			error: function(err) {
				console.log(err)
			}

		})
	})
})

$('.select_menAnd_wormen').change((e) => {
	//alert($('#select_menAnd_wormen option:selected').text());
	str = $('#select_menAnd_wormen option:selected').text();

});

//接待列表是否为空
function dont_online(data) {
	if($('.list-group').children("li").length == 0) {
		$(".list-group").html('<img src="img/haha.png" class="Dontonline"/>');
		$(".guyitang").css("display", "block");
		$(".chatroom").css("display", "none"); //聊天界面隐藏
	} else {
		//当客服没有进入房间隐藏
		if(!($(".username").attr("data-id"))) {
			$(".guyitang").css("display", "block");
			$(".chatroom").css("display", "none"); //聊天界面隐藏
		} else {
			$(".chatroom").css("display", "block"); //聊天界面隐藏
			$(".guyitang").css("display", "none");
		}
	}
};

//记录指派医生成功的信息
var assigned_doctor = [];
var auditResult_id = {};
var date_cc = '';
//查看聊天记录
function findchat(datas) {
	let msg = window.sessionStorage['user_msg'];
	msg = JSON.parse(msg);
	$.ajax({
		url: serviceURL + "findchat",
		type: "post",
		dataType: "json",
		data: datas,
		headers: {
			'Authorization': 'Bearer ' + msg.token
		},
		success: function(res) {
			console.log(res)
			$('.chat-thread').children("div").remove()
			let datas = res.data;
			let data_Arr = [];
			if(res.code == 200) {
				for(let a = 0; a < datas.length; a++) {
					if(datas[a].username == $("#name").attr("data-username")) {
						var datestr = '';
						if(a > 0) {
							if(datas[a].senddate.split(",")[0] != datas[a - 1].senddate.split(",")[0]) {
								datestr = datas[a - 1].senddate.split(",")[0];
								$('.chat-thread').prepend('<div class="layim-chat-system"><span layim-event="chatLog"><a>' + datestr + '</a></span></div>');
							}
						} else {
							datestr = date_cc;
							$('li[date-show="' + datas[a].senddate.split(",")[0] + '"]').length == 0 ?
								$('.chat-thread').prepend('<div class="layim-chat-system"><span layim-event="chatLog"><a>' + datestr + '</a></span></div>') : '';
						}
						if(datas[a].imggs) {
							let html = `<li class="layim-chat-mine" date-show="${datas[a].senddate.split(",")[0]}">
							<div class="layim-chat-user">
								<img src="https://xcximg.juseyun.com/Images/servers.png">
									<cite><i>${datas[a].username}</i>${datas[a].senddate.split(",")[1]}</cite>
									</div>
								<div class="layim-chat-text" style="color:white;background-color:#1abb9c;" >
								   <img class="chatimg" src="${datas[a].imggs}">
								</div>
						   </li>`
							$('.chat-thread').prepend(html);
						} else {
							let html = `<li class="layim-chat-mine" date-show="${datas[a].senddate.split(",")[0]}">
					<div class="layim-chat-user">
						<img src="https://xcximg.juseyun.com/Images/servers.png">
							<cite><i>${datas[a].username}</i>${datas[a].senddate.split(",")[1]}</cite>
							</div>
							<div class="layim-chat-text" style="color:white;background-color=;background-color:#1abb9c;">${datas[a].msg}</div>
						</li>`
							$('.layim-chat-main>ul').prepend(html);
						}
					} else {

						var datestr = '';
						if(a > 0) {
							if(datas[a].senddate.split(",")[0] != datas[a - 1].senddate.split(",")[0]) {
								datestr = datas[a - 1].senddate.split(",")[0];
								$('.chat-thread').prepend('<div class="layim-chat-system"><span layim-event="chatLog"><a>' + datestr + '</a></span></div>');
							}
						} else {
							datestr = date_cc;
							$('li[date-show="' + datas[a].senddate.split(",")[0] + '"]').length == 0 ?
								$('.chat-thread').prepend('<div class="layim-chat-system"><span layim-event="chatLog"><a>' + datestr + '</a></span></div>') : '';
						}
						//if(datas[a].username == $(".closes").attr("data-id")) {
						if(datas[a].imggs) {
							//let html = '<li class="say_layout"><div class="Tosay"><div class="left-Text"><div class="left-d"><hr><span class="span_times">' + (datas[a].username) + '&nbsp;' + (datas[a].senddate) + '</span> <divclass="a3"><img  class="chatimg" src="' + datas[a].imggs + '"/></div></div></div></div></li>';
							let htmls = `<li date-show="${datas[a].senddate.split(",")[0]}">
								<div class="layim-chat-user">
								<img src="${datas[a].anonymityImg}">
								<cite>${datas[a].username}<i>${datas[a].senddate.split(",")[1]}</i></cite>
								</div>
								<div class="layim-chat-text" style="color: #18BB9B;">
								<img class="chatimg" src="${datas[a].imggs}">
								</div>
								</li>`
							$('.chat-thread').prepend(htmls);
						} else {
							//let html = '<li class="say_layout"><div class="Tosay"><div class="left-Text"><div class="left-d"><hr><span class="span_times">' + (datas[a].username) + "   " + (datas[a].senddate) + '</span><div  class="a3">' + datas[a].msg + '</div></div></div></div></li>';
							let htmls = `<li date-show="${datas[a].senddate.split(",")[0]}">
							<div class="layim-chat-user">
							<img src="${datas[a].anonymityImg}">
							<cite>${datas[a].username}<i>${datas[a].senddate.split(",")[1]}</i></cite>
							</div>
							<div class="layim-chat-text" style="color: #18BB9B;">
							  <p>${datas[a].msg}</p>
							</div>
							</li>`
							$('.chat-thread').prepend(htmls)
						}
						//}
					};
					let div = document.getElementsByClassName('chat-thread')[0];
					div.scrollTop = div.scrollHeight;
				};
				if(datas.length > 0) {
					$('.chat-thread').append('<div class="layim-chat-system"><span layim-event="chatLog"><a>以上是历史聊天记录</a></span></div>');
					date_cc = datas[datas.length - 1].senddate.split(",")[0];
				}
			};
		},
		error: function(err) {
			console.log(err)
		}
	})
};

function findchats(datas) {
	let msg = window.sessionStorage['user_msg'];
	msg = JSON.parse(msg);
	$.ajax({
		url: serviceURL + "findchat",
		type: "post",
		dataType: "json",
		data: datas,
		headers: {
			'Authorization': 'Bearer ' + msg.token
		},
		success: function(res) {
			console.log(res)
			let datas = res.data;
			if(res.code == 200) {
				for(let a = 0; a < datas.length; a++) {
					if(datas[a].username == $("#name").attr("data-username")) {
						var datestr = '';
						if(a > 0) {
							if(datas[a].senddate.split(",")[0] != datas[a - 1].senddate.split(",")[0]) {
								datestr = datas[a - 1].senddate.split(",")[0];
								$('.chat-thread').prepend('<div class="layim-chat-system"><span layim-event="chatLog"><a>' + datestr + '</a></span></div>');
							}
						} else {
							datestr = date_cc;
							$('li[date-show="' + datas[a].senddate.split(",")[0] + '"]').length == 0 ?
								$('.chat-thread').prepend('<div class="layim-chat-system"><span layim-event="chatLog"><a>' + datestr + '</a></span></div>') : '';
						}
						if(datas[a].imggs) {
							let html = `<li class="layim-chat-mine" date-show="${datas[a].senddate.split(",")[0]}">
							<div class="layim-chat-user">
								<img src="https://xcximg.juseyun.com/Images/servers.png">
									<cite><i>${datas[a].username}</i>${datas[a].senddate.split(",")[1]}</cite>
									</div>
								<div class="layim-chat-text" style="color:white;background-color:#1abb9c;" >
								   <img class="chatimg" src="${datas[a].imggs}">
								</div>
						   </li>`
							$('.chat-thread').prepend(html);
						} else {
							let html = `<li class="layim-chat-mine" date-show="${datas[a].senddate.split(",")[0]}">
					    <div class="layim-chat-user">
						<img src="https://xcximg.juseyun.com/Images/servers.png">
							<cite><i>${datas[a].username}</i>${datas[a].senddate.split(",")[1]}</cite>
							</div>
							<div class="layim-chat-text" style="color:white;background-color=;background-color:#1abb9c;">${datas[a].msg}</div>
						</li>`
							$('.layim-chat-main>ul').prepend(html);
						}
					} else {
						var datestr = '';
						if(a > 0) {
							if(datas[a].senddate.split(",")[0] != datas[a - 1].senddate.split(",")[0]) {
								datestr = datas[a - 1].senddate.split(",")[0];
								$('.chat-thread').prepend('<div class="layim-chat-system"><span layim-event="chatLog"><a>' + datestr + '</a></span></div>');
							}
						} else {
							datestr = date_cc;
							$('li[date-show="' + datas[a].senddate.split(",")[0] + '"]').length == 0 ?
								$('.chat-thread').prepend('<div class="layim-chat-system"><span layim-event="chatLog"><a>' + datestr + '</a></span></div>') : '';
						}
						//if(datas[a].username == $(".closes").attr("data-id")) {
						if(datas[a].imggs) {
							//let html = '<li class="say_layout"><div class="Tosay"><div class="left-Text"><div class="left-d"><hr><span class="span_times">' + (datas[a].username) + '&nbsp;' + (datas[a].senddate) + '</span> <divclass="a3"><img  class="chatimg" src="' + datas[a].imggs + '"/></div></div></div></div></li>';
							let htmls = `<li date-show="${datas[a].senddate.split(",")[0]}">
								<div class="layim-chat-user">
								<img src="${datas[a].anonymityImg}">
								<cite>${datas[a].username}<i>${datas[a].senddate.split(",")[1]}</i></cite>
								</div>
								<div class="layim-chat-text" style="color: #18BB9B;">
								<img class="chatimg" src="${datas[a].imggs}">
								</div>
								</li>`

							$('.chat-thread').prepend(htmls);
						} else {
							//let html = '<li class="say_layout"><div class="Tosay"><div class="left-Text"><div class="left-d"><hr><span class="span_times">' + (datas[a].username) + "   " + (datas[a].senddate) + '</span><div  class="a3">' + datas[a].msg + '</div></div></div></div></li>';
							let htmls = `<li date-show="${datas[a].senddate.split(",")[0]}">
							<div class="layim-chat-user">
							<img src="${datas[a].anonymityImg}">
							<cite>${datas[a].username}<i>${datas[a].senddate.split(",")[1]}</i></cite>
							</div>
							<div class="layim-chat-text" style="color: #18BB9B;">
							  <p>${datas[a].msg}</p>
							</div>
							</li>`
							$('.chat-thread').prepend(htmls)
						}
					};
				};
				if(datas.length > 0) {
					date_cc = datas[datas.length - 1].senddate.split(",")[0];
				}
			};
		},
		error: function(err) {
			console.log(err)
		}
	})
};
//审核状态查询
function auditResult(_id, datas) {
	$.ajax({
		url: serviceURL + "auditResult",
		type: "post",
		dataType: "json",
		data: {
			_id: _id,
			userid: datas
		},
		success: function(res) {
			console.log(res);
			if(res.code == 200) {
				if(res.data.result) {
					$(".Assigned_tothe_doctor").text("医生审核通过");
				}
			}
		},
		error: function(err) {
			console.log(err)
		}
	})
};

//聊天室用户基本信息
function temporary_info(data) {
	$.ajax({
		url: serviceURL + "temporary",
		type: "post",
		dataType: "json",
		data: {
			roomname: data,
			content: {

			}
		},
		success: function(res) {
			console.log(res);
			if(res.code == 200) {
				if(res.data.result) {
					$(".Assigned_tothe_doctor").text("医生审核通过");
				}
			}
		},
		error: function(err) {
			console.log(err)
		}
	})
};

//获取房间缓存用户信息
function gettemporary(roomid) {
	let msg = window.sessionStorage['user_msg'];
	msg = JSON.parse(msg);
	$.ajax({
		url: serviceURL + "get_temporary",
		type: "post",
		dataType: "json",
		data: {
			roomname: roomid
		},
		headers: {
			'Authorization': 'Bearer ' + msg.token
		},
		success: function(res) {
			console.log(res);
			if(res.code == 200) {
				let data = res.content;
				//基本收集单数据
				if(data.information) {
					let information = JSON.parse(data.information);
					if(data.gender == 1) {
						//男性
						//senduserinfo(data); //保存用户信息
						$('div[roomid="' + roomid + '"] .biaodaninfo').css("display", "none");
						$('div[roomid="' + roomid + '"] .drawing_input').css("display", "block");

						//选择收集单
						$('div[roomid="' + roomid + '"] .Collect_the_single').css("display", "none");

						$('div[roomid="' + roomid + '"] .Send_the_basic_information_form_drug').css("display", "none");

						//修改按钮显示
						$('div[roomid="' + roomid + '"] .modification').css("display", "none");
						//发送基本信息表单按钮隐藏
						$('div[roomid="' + roomid + '"] .Send_the_basic_information_form').css("display", "none");
						$('div[roomid="' + roomid + '"] .gender_all').children().remove();
						let htmls = '<div class="gender_all_men">';
						htmls += '<span class="all_men">男</span>';
						htmls += '</div>';
						$('div[roomid="' + roomid + '"] .gender_all').append(htmls);

						$('div[roomid="' + roomid + '"] .username_S_left').text(data.name);
						$('div[roomid="' + roomid + '"] .riqi').text(data.birthday);
						$('div[roomid="' + roomid + '"] .height_S_left').text(data.height);
						$('div[roomid="' + roomid + '"] .weight_S_left').text(data.weight);

						if(data.medicalHistory || data.allergy) {
							$('div[roomid="' + roomid + '"] .input_medical_left').text(data.medicalHistory);
							$('div[roomid="' + roomid + '"] .input_allergy_left').text(data.allergy);
						} else {
							$('div[roomid="' + roomid + '"] .input_medical_left').text("无");
							$('div[roomid="' + roomid + '"] .input_allergy_left').text("无");
						};
						//数据渲染
						$("div[roomid='" + roomid + "'] .System_in_the_diagnosis_of").text(data.systenm);
						$("div[roomid='" + roomid + "'] .service_of_").val(data.servicetext);
						//药品显示
						let serMedicinal = JSON.parse(data.serMedicinal);
						suggestdrug[roomid] = serMedicinal;
						let htmls_ = "";
						for(let p = 0; p < serMedicinal.length; p++) {
							htmls_ +=
								`			  <!-- 标签展示 -->
				  <div class="Drug_labels_all_">
				                                  <div class="Drug_labels_all_">
                                               
                                                                        <div class="Drug_labels_all_s"  data-productID="${serMedicinal[p].productid}">
                                                                                <!-- 删除标签 -->
                                                       <a href="http://47.97.17.157:3000/html/Details.html?productId=${serMedicinal[p].productid}" title="${serMedicinal[p].productname}" target="_blank"> ${serMedicinal[p].productname} </a>                                                                             
                                                                        </div>
                                                                        <!-- <span class="close_Drug">X</span> -->
                                                                        <!--  输入框  -->
                                                                        <input type="number" style=" " data-productID="${serMedicinal[p].productid}" class="number_select_" value="${serMedicinal[p].count}" onblur="onBlur(event)">                                                                      
                                              </div>						
				  </div>				 				     
				  `
						}
						$("div[roomid='" + roomid + "'] .Drug_labels .Scroll_area").html(htmls_);
						let suject_datas = JSON.parse(data.informations)[0].subject;
						let formDate = '';
						for(var b = 0; b < suject_datas.length; b++) {
							//console.log(suject_datas[b])
							if(suject_datas[b].type == 1) { //单选
								if(suject_datas[b].select instanceof Array) {
									let str = '';
									for(let a = 0; a < suject_datas[b].select.length; a++) {
										if(suject_datas[b].select[a].checked == true) {
											str += `<div class="color_all_style">
								<input type="radio" name="order${b}" checked disabled class="input_all_style" value="${suject_datas[b].select[a].selectResult}">
								<span>${suject_datas[b].select[a].selectResult}</span>
							</div>`
										} else {
											str += `<div class="color_all_style">
								<input type="radio" name="order${b}" disabled class="input_all_style" value="${suject_datas[b].select[a].selectResult}">
								<span>${suject_datas[b].select[a].selectResult}</span>
							</div>`
										}
									};
									let formDates = `<div class="user_news_all_" data_item="${b}" data_index='${suject_datas[b].type}'>${b+1}、${suject_datas[b].subjectName}(单选)
					                <div class="Day_to_day_A">${str}</div>
				             	  </div>`
									formDate += formDates;
								};
							};
							if(suject_datas[b].type == 2) { //多选
								if(suject_datas[b].select instanceof Array) {
									let str = '';
									for(let a = 0; a < suject_datas[b].select.length; a++) {
										if(suject_datas[b].select[a].checked == true) {
											str += `<div class="color_all_style">
														<input type="checkbox" name="order${b}" checked disabled class="input_all_style" value="${suject_datas[b].select[a].selectResult}">
														<span>${suject_datas[b].select[a].selectResult}</span>
							</div>`
										} else {
											str += `<div class="color_all_style">
														<input type="checkbox" name="order${b}" disabled class="input_all_style" value="${suject_datas[b].select[a].selectResult}">
														<span>${suject_datas[b].select[a].selectResult}</span>
							</div>`
										}

									};
									let formDates = `<div class="user_news_all_" data_item="${b}" data_index='${suject_datas[b].type}'>${b+1}、${suject_datas[b].subjectName}(多选)
					<div class="Day_to_day_A">${str}</div>
					</div>`;
									formDate += formDates;
								};
							};
							if(suject_datas[b].type == 3) { //简答
								let str = `<textarea name="textareas" disabled class="textarea${b+1}" style='margin-left: -20px;width: 100%;height: 70px;background: white;border-radius: 5px;'>${suject_datas[b].describe}</textarea>`
								let formDates = `<div class="user_news_all_" data_item="${b}" data_index='${suject_datas[b].type}'>${b+1}、${suject_datas[b].subjectName}(简答)
									<div class="Day_to_day_A">${str}</div>
									</div>`;
								formDate += formDates;

							};
							if(suject_datas[b].type == 4) { //图片
								let stars = ``;
								for(let a = 0; a < suject_datas[b].img.length; a++) {
									stars += `<div class="show_imgs"><img src="${suject_datas[b].img[a]}" class="layui-upload-img"></div>`
								}
								let str = `<div class="" style=" display: flex;	flex-direction: row;flex-wrap: wrap; " > 
								<div style="height:110px;" >
								    <div class="layui-upload-list" style="height: 93px;margin:0 5px;display: flex;flex-direction: row  ">
								      ${stars}
								    </div>
								</div>
								<div class="layui-upload">
									 <img src="img/uploadimg.png" class="upload_Orderimg"/>
									  <input type="file" name="files"  class="upload_img" imgsize="${suject_datas[b].img.length}" onchange="creatImg(this.files,this)" />
								</div>	
						    </div>`
								let formDates = `<div class="user_news_all_" data_item="${b}" data_index='${suject_datas[b].type}' style="display: flex;	flex-direction: column;">
								    <p>${b+1}、${suject_datas[b].subjectName}(图片) </p>
									<div class="Day_to_day_A">${str}</div>
									</div>`;
								formDate += formDates;
							};
						};
						$('div[roomid="' + roomid + '"] .men_input_change_three').html(formDate);
						$('div[roomid="' + roomid + '"] .men_input_change .upload_Orderimg').css("display", "none");
						$('div[roomid="' + roomid + '"] .men_input_change').css('display', 'block');
						$("div[roomid='" + roomid + "'] .substitute_women").children().remove();
						$("div[roomid='" + roomid + "'] .Collect_the_singles").css("margin-top", "0px");
						$('div[roomid="' + roomid + '"]').attr("_id", data._id);
						$("div[roomid='" + roomid + "']").attr("uderinfo_id", data.mesId);
						$("div[roomid='" + roomid + "']").attr("subject_id", data.subject_id);
						$("div[roomid='" + roomid + "']").attr("receiveId", data.receiveId);
					} else {
						//女性
						let data = res.content;
						//senduserinfo(data); //保存用户信息
						$('div[roomid="' + roomid + '"] .biaodaninfo').css("display", "none");
						$('div[roomid="' + roomid + '"] .drawing_input').css("display", "block");

						//选择收集单
						$('div[roomid="' + roomid + '"] .Collect_the_single').css("display", "none");

						$('div[roomid="' + roomid + '"] .Send_the_basic_information_form_drug').css("display", "none");

						//修改按钮显示
						$('div[roomid="' + roomid + '"] .modification').css("display", "none");
						//发送基本信息表单按钮隐藏
						$('div[roomid="' + roomid + '"] .Send_the_basic_information_form').css("display", "none");
						$('div[roomid="' + roomid + '"] .gender_all').children().remove();
						let htmls = '<div class="gender_all_wormen">';
						htmls += '<span class="wormen">女</span>';
						htmls += '</div>';
						$('div[roomid="' + roomid + '"] .gender_all').append(htmls);

						$('div[roomid="' + roomid + '"] .username_S_left').text(data.name);
						$('div[roomid="' + roomid + '"] .riqi').text(data.birthday);
						$('div[roomid="' + roomid + '"] .height_S_left').text(data.height);
						$('div[roomid="' + roomid + '"] .weight_S_left').text(data.weight);

						if(data.medicalHistory || data.allergy) {
							$('div[roomid="' + roomid + '"] .input_medical_left').text(data.medicalHistory);
							$('div[roomid="' + roomid + '"] .input_allergy_left').text(data.allergy);
						} else {
							$('div[roomid="' + roomid + '"] .input_medical_left').text("无");
							$('div[roomid="' + roomid + '"] .input_allergy_left').text("无");
						};
						//数据渲染
						$("div[roomid='" + roomid + "'] .System_in_the_diagnosis_of").text(data.systenm);
						$("div[roomid='" + roomid + "'] .service_of_").val(data.servicetext);
						//数据渲染
						$("div[roomid='" + roomid + "'] .substitute").css("display", "none");
						$("div[roomid='" + roomid + "'] .men_input_change").css({
							'display': 'none'
						});
						$("div[roomid='" + roomid + "'] .substitute_women").children().remove();
						$("div[roomid='" + roomid + "'] .Collect_the_singles").css("margin-top", "0px");

						$("div[roomid='" + roomid + "'] .substitute_women").css("display", "block");
						$("div[roomid='" + roomid + "'] .woman_confirm").css("display", "none");
						$("div[roomid='" + roomid + "'] .woman_cancel").css("display", "none");
						let suject_datas = JSON.parse(data.informations)[0].subject;
						console.log(suject_datas);
						let formDate = '';
						for(var b = 0; b < suject_datas.length; b++) {
							//console.log(suject_datas[b])
							if(suject_datas[b].type == 1) { //单选
								if(suject_datas[b].select instanceof Array) {
									let str = '';
									for(let a = 0; a < suject_datas[b].select.length; a++) {
										if(suject_datas[b].select[a].checked == true) {
											str += `<div class="color_all_style">
								<input type="radio" name="order${b}" checked disabled class="input_all_style" value="${suject_datas[b].select[a].selectResult}">
								<span>${suject_datas[b].select[a].selectResult}</span>
							</div>`
										} else {
											str += `<div class="color_all_style">
								<input type="radio" name="order${b}" disabled class="input_all_style" value="${suject_datas[b].select[a].selectResult}">
								<span>${suject_datas[b].select[a].selectResult}</span>
							</div>`
										}
									};
									let formDates = `<div class="user_news_all_" data_item="${b}" data_index='${suject_datas[b].type}'>${b+1}、${suject_datas[b].subjectName}(单选)
					<div class="Day_to_day_A">${str}</div>
					</div>`;
									formDate += formDates;
								};
							};
							if(suject_datas[b].type == 2) { //多选
								if(suject_datas[b].select instanceof Array) {
									let str = '';
									for(let a = 0; a < suject_datas[b].select.length; a++) {
										if(suject_datas[b].select[a].checked == true) {
											str += `<div class="color_all_style">
														<input type="checkbox" name="order${b}" checked disabled class="input_all_style" value="${suject_datas[b].select[a].selectResult}">
														<span>${suject_datas[b].select[a].selectResult}</span>
							</div>`
										} else {
											str += `<div class="color_all_style">
														<input type="checkbox" name="order${b}" disabled class="input_all_style" value="${suject_datas[b].select[a].selectResult}">
														<span>${suject_datas[b].select[a].selectResult}</span>
							</div>`
										}

									};
									let formDates = `<div class="user_news_all_" data_item="${b}" data_index='${suject_datas[b].type}'>${b+1}、${suject_datas[b].subjectName}(多选)
					<div class="Day_to_day_A">${str}</div>;
					</div>`;
									formDate += formDates;
								};
							};
							if(suject_datas[b].type == 3) { //简答
								let str = `<textarea name="textareas" disabled class="textarea${b+1}" style='margin-left: -20px;width: 100%;height: 70px;background: white;border-radius: 5px;'>${suject_datas[b].describe}</textarea>`
								let formDates = `<div class="user_news_all_" data_item="${b}" data_index='${suject_datas[b].type}'>${b+1}、${suject_datas[b].subjectName}(简答)
									<div class="Day_to_day_A">${str}</div>
									</div>`;
								formDate += formDates;

							};
							if(suject_datas[b].type == 4) { //图片
								let stars = ``;
								for(let a = 0; a < suject_datas[b].img.length; a++) {
									stars += `<div class="show_imgs"><img src="${suject_datas[b].img[a]}" class="layui-upload-img"></div>`
								}
								let str = `<div class="" style=" display: flex;	flex-direction: row;flex-wrap: wrap; " > 
								<div style="height:110px;" >
								    <div class="layui-upload-list" style="height: 93px;margin:0 5px;display: flex;flex-direction: row  ">
								      ${stars}
								    </div>
								</div>
								<div class="layui-upload">
									 <img src="img/uploadimg.png" class="upload_Orderimg"/>
									  <input type="file" name="files"  class="upload_img" imgsize="${suject_datas[b].img.length}" onchange="creatImg(this.files,this)" />
								</div>	
						    </div>`
								let formDates = `<div class="user_news_all_" data_item="${b}" data_index='${suject_datas[b].type}' style="display: flex;	flex-direction: column;">
								    <p>${b+1}、${suject_datas[b].subjectName}(图片) </p>
									<div class="Day_to_day_A">${str}</div>
									</div>`;
								formDate += formDates;
							};
						};
						$('div[roomid="' + roomid + '"] .men_input_change_three').html(formDate);
						$('div[roomid="' + roomid + '"] .men_input_change .upload_Orderimg').css("display", "none");
						$('div[roomid="' + roomid + '"] .men_input_change').css('display', 'block');
						$("div[roomid='" + roomid + "'] .substitute_women").children().remove();
						$("div[roomid='" + roomid + "'] .Collect_the_singles").css("margin-top", "0px");
						//药品显示
						let serMedicinal = JSON.parse(data.serMedicinal);
						suggestdrug[roomid] = serMedicinal;
						let htmls_ = "";
						for(let p = 0; p < serMedicinal.length; p++) {
							htmls_ +=
								`			  <!-- 标签展示 -->
				  <div class="Drug_labels_all_">
				                                  <div class="Drug_labels_all_">
                                             
                                                                        <div class="Drug_labels_all_s"  data-productID="${serMedicinal[p].productid}">
                                                                                <!-- 删除标签 -->
                                                                        <a href="http://47.97.17.157:3000/html/Details.html?productId=${serMedicinal[p].productid}" title="${serMedicinal[p].productname}" target="_blank"> ${serMedicinal[p].productname} </a>
                                                                                                                                                               
                                                                        </div>
                                                                        <!-- <span class="close_Drug">X</span> -->
                                                                        <!--  输入框  -->
                                                                        <input type="number" style=" " data-productID="${serMedicinal[p].productid}" class="number_select_" value="${serMedicinal[p].count}" onblur="onBlur(event)">                                                                                                                                             
                                            </div>
				  </div>				 				     
				  `

						}
						$("div[roomid='" + roomid + "'] .Drug_labels .Scroll_area").html(htmls_);
					};
				};
				if(data.mesId){
					$(".Assigned_tothe_doctor").text(data.state);
				}
				//				$(".Assigned_tothe_doctor").attr("disabled", "disabled");
				//				$(".Assigned_tothe_doctor").css("color", "#333333");
				//				$(".Assigned_tothe_doctor").css("border", "1px solid #333333");
				$('div[roomid="' + roomid + '"]').attr("_id", data._id);
				$("div[roomid='" + roomid + "']").attr("uderinfo_id", data.mesId);
				$("div[roomid='" + roomid + "']").attr("subject_id", data.subject_id);
				$("div[roomid='" + roomid + "']").attr("receiveId", data.receiveId);
				$("div[roomid='" + roomid + "'] .modification").css("display", "none");
			}
		},
		error: function(err) {
			console.log(err)
		}
	});
};

//结束服务删除房间用户缓存数据
function del_temporary(roomid) {
	let msg = window.sessionStorage['user_msg'];
	msg = JSON.parse(msg);
	$.ajax({
		url: serviceURL + "del_temporary",
		type: "post",
		dataType: "json",
		data: {
			roomname: roomid
		},
		headers: {
			'Authorization': 'Bearer ' + msg.token
		},
		success: function(res) {

		},
		error: function(err) {

		}
	})
};

//删除缓存药品数据
function img_delete(e) {
	let roomid = $(".username").attr("data-id"); //房间id
	console.log(suggestdrug[roomid])
	console.log($(e.target).parents('.Drug_labels_all_'))
	console.log($(e.target)[0].dataset.index)

	let index = $(e.target)[0].dataset.index

	suggestdrug[roomid].splice(index, 1)

	console.log(suggestdrug[roomid])

	$(e.target).parents('.Drug_labels_all_').remove()
};
//房间人数
socket.on("userinfo_room", function(data) {
	console.log(data)
})